#include "stdafx.h"
#include "UIButton.h"
#include "Render.h"

CUIButton::CUIButton(void)
{
	m_nStatus = Button_Status_Normal;
	m_pData = NULL;
	m_bSwitch = FALSE;
	m_nFrameCount = 4;
}

CUIButton::~CUIButton(void)
{
	
}

void CUIButton::Create(CString szImageFile, CRect rcBound, CUIControl *pParent, int nFrameCount)
{
	CUIControl::CreateUI(rcBound, pParent);
    m_imgButton.Load(szImageFile); 
	m_nFrameCount = nFrameCount;
}

void CUIButton::SetImage(const char *szImageFile, int nFrameCount)
{
    m_imgButton.Load(szImageFile);
	m_nFrameCount = nFrameCount;
}

void CUIButton::SetSwitchImage(const char *szSwitchImageFile)
{
	m_imgSwitchButton.Load(szSwitchImageFile);
}

BOOL CUIButton::OnMouseOver(UINT nFlags, CPoint point)
{
	if(m_nStatus == Button_Status_Disabled)
		return FALSE;
	if(m_nStatus == Button_Status_Normal)
	{
		m_nStatus = Button_Status_Focused;
		InvalidateUI();
	}
	return TRUE;
}

BOOL CUIButton::OnMouseOut()
{
	if(m_nStatus == Button_Status_Disabled)
		return FALSE;
	if(m_nStatus != Button_Status_Normal)
	{
		m_nStatus = Button_Status_Normal;
		InvalidateUI();
	}
	return TRUE;
}

BOOL CUIButton::OnLButtonDown(UINT nFlags, CPoint point)
{
	if(m_nStatus == Button_Status_Disabled)
		return FALSE;
	m_nStatus = Button_Status_Pushed;
	InvalidateUI();
	return TRUE;
}

BOOL CUIButton::OnLButtonUp(UINT nFlags, CPoint point)
{
	if(m_nStatus == Button_Status_Disabled)
		return FALSE;
	if(m_nStatus == Button_Status_Pushed)
	{
		m_nStatus = Button_Status_Focused;
		InvalidateUI();

		UIAction action;
		action.pUISource = this;
		action.dwAction = UIAction_Button_Click;
		m_pContainer->PerformAction(action);
	}
	return TRUE;
}

void CUIButton::Render(CDC *pDC)
{
	if(!m_imgButton.IsValid())
		return;
	CRect rcBound = CRect(0, 0, m_rcBound.Width(), m_rcBound.Height());
	Child2Window(rcBound);
	int nButtonWidth = m_imgButton.GetWidth() / m_nFrameCount;
	int nButtonHeight = m_imgButton.GetHeight();
	int nLeft = m_nStatus * nButtonWidth;

	if(m_bSwitch && m_imgSwitchButton.IsValid())
        m_imgSwitchButton.DrawPart(pDC->m_hDC, rcBound, CRect(nLeft, 0, nLeft + nButtonWidth, nButtonHeight));
	else
	    m_imgButton.DrawPart(pDC->m_hDC, rcBound, CRect(nLeft, 0, nLeft + nButtonWidth, nButtonHeight));
}

